import requests
import json
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
from config import Config

def chat_with_llm(messages, stream=True):
    """
    使用对话API与大模型进行交互
    
    Args:
        messages: 消息列表，格式为[{"role": "user", "content": "问题内容"}]
        stream: 是否使用流式返回，默认为True
    """
    url = Config.LLM_API_BASE_URL + "/chat"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "messages": messages,
        "stream": stream
    }
    
    if stream:
        # 流式返回处理
        try:
            response = requests.post(url, headers=headers, json=data, stream=True)
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            return {"error": f"请求失败: {str(e)}"}

        with response:
            
            full_response = []
            for line in response.iter_lines():
                if line:
                    line = line.decode('utf-8')
                    if line.startswith("data: "):
                        data = line[6:]
                        
                        if data == "[DONE]":
                            break
                        
                        try:
                            parsed = json.loads(data)
                            full_response.append(parsed)
                        except json.JSONDecodeError:
                            return {"error": f"JSON解析失败: {data}"}
            
            return full_response
    else:
        # 非流式返回处理
        response = requests.post(url, headers=headers, json=data)
        try:
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            return {"error": f"请求失败: {str(e)}"}
        except json.JSONDecodeError:
            return {"error": f"响应不是有效的JSON: {response.text}"}
        

def search_with_api(query, provider="sogou", limit=5, use_proxy=True):
    """
    调用搜索API获取搜索结果
    
    Args:
        query: 搜索关键词
        provider: 搜索提供商(google/searchapi/sogou)，默认为sogou
        limit: 搜索结果数量限制，默认为5
        use_proxy: 是否使用代理，默认为True
    
    Returns:
        {"data": results} 或 {"error": message} 格式的JSON对象
    """
    url = Config.LLM_API_SOU_URL + "/search"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "query": query,
        "provider": provider,
        "limit": limit,
        "use_proxy": use_proxy
    }
    
    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        result = response.json()
        
        if "error" in result:
            return {"error": result["error"]}
        return {"data": result.get("results", [])}
            
    except requests.exceptions.RequestException as e:
        return {"error": f"请求失败: {str(e)}"}
    except json.JSONDecodeError:
        return {"error": f"无效的JSON响应: {response.text}"}

if __name__ == "__main__":
    pass  # 测试代码已迁移到单独文件
